import React from 'react';
import ReactDOM from 'react-dom';
import {PullToRefresh, ListView,} from 'antd-mobile';
import request from "@/utils/request";
import {uuid} from "@/utils";

let data = [];
const NUM_ROWS = 20;
let pageIndex = 0;

function genData(pIndex = 0) {
  const dataArr = [];
  for (let i = 0; i < NUM_ROWS; i++) {
    dataArr.push(`row - ${(pIndex * NUM_ROWS) + i}`);
    data.push(
      {
        img: 'https://zos.alipayobjects.com/rmsportal/hfVtzEhPzTUewPm.png',
        title: 'Eat the week',
        des: '不是所有的兼职汪都需要风吹日晒',
      },
    )
  }
  return dataArr;
}

function genData1(pIndex = 0) {
  const dataArr = [];
  for (let i = 0; i < NUM_ROWS; i++) {
    dataArr.unshift(`row - ${(pIndex * NUM_ROWS) + i}`);
    data.unshift(
      {
        img: 'https://zos.alipayobjects.com/rmsportal/hfVtzEhPzTUewPm.png',
        title: `Eat the week ${pIndex}`,
        des: '不是所有的兼职汪都需要风吹日晒',
      },
    )
  }
  return dataArr;
}


class ConListView extends React.Component {
  constructor(props) {
    super(props);
    const dataSource = new ListView.DataSource({
      rowHasChanged: (row1, row2) => row1 !== row2,
    });
    this.state = {
      dataSource,
      refreshing: true,
      isLoading: true,
      height: document.documentElement.clientHeight,
      useBodyScroll: true,
      count: 1,
    };
  }

  // 下拉列表数据
  dataList = [];

  componentDidUpdate() {
    if (this.state.useBodyScroll) {
      document.body.style.overflow = 'auto';
    } else {
      document.body.style.overflow = 'hidden';
    }
  }

  async componentDidMount() {
    // 获取据顶的高
    const hei = this.state.height - ReactDOM.findDOMNode(this.lv).offsetTop;
    // todo 前后约定
    let result = await this.getService({});
    let {list = []} = result?.data;

    let dataSource = this.genData(list);
    this.setState({
      dataSource: this.state.dataSource.cloneWithRows(dataSource),
      height: hei,
      refreshing: false,
      isLoading: false,
    });
  }


  /**
   * 将后端数据转换成列表组件格式数据
   * @param arr  待转换待数据
   * @param rowId 行数据唯一字段
   * @returns {[]}
   */
  genData = (arr, rowId = "id") => {
    let dataArr = [];
    for (let index = 0; index < arr.length; index++) {
      let item = arr[index];
      // 判断是否有唯一行标识字段
      let tempRowId = arr[index][rowId];
      if (!tempRowId) {
        tempRowId = uuid();
        item[rowId] = tempRowId;
      }

      dataArr.push(tempRowId); // 添加行id
      this.dataList[tempRowId] = item;
    }
    return dataArr;
  }


  //todo 可以根据项目修改 前后端预定
  getService = (payload = {}) => {
    const {url} = this.props;
    return request(url, {
      method: 'POST',
      data: payload,
    });
  };


  // 下拉刷新价值
  onRefresh = () => {
    this.setState({refreshing: true, isLoading: true});
    setTimeout(() => {
      this.rData = genData1(100);
      this.setState({
        dataSource: this.state.dataSource.cloneWithRows(genData()),
        refreshing: false,
        isLoading: false,
      });
    }, 600);
  };


  // 底部上拉刷新
  onEndReached = async (event) => {
    if (this.state.isLoading && !this.state.hasMore) {
      return;
    }
    this.setState({isLoading: true});

    // setTimeout(() => {
    //   this.rData = [...this.rData, ...genData(++pageIndex)];
    //   this.setState({
    //     dataSource: this.state.dataSource.cloneWithRows(this.rData),
    //     isLoading: false,
    //   });
    // }, 1000);
  };

  render() {

    const separator = (sectionID, rowID) => (
      <div
        key={`${sectionID}-${rowID}`}
        style={{
          backgroundColor: '#F5F5F9',
          height: 8,
          borderTop: '1px solid #ECECED',
          borderBottom: '1px solid #ECECED',
        }}
      />
    );

    const row = (rowID, sectionID) => {
      const rowObj = this.dataList[rowID]; // 行数据
      if (!rowObj) {
        return null;
      }
      return (
        <div key={rowID}
             style={{
               padding: '0 15px',
               backgroundColor: 'white',
             }}
        >
          <div style={{
            height: '50px',
            lineHeight: '50px',
            color: '#888',
            fontSize: '18px',
            borderBottom: '1px solid #ddd'
          }}>
            {rowObj.title}
          </div>
          <div style={{display: '-webkit-box', display: 'flex', padding: '15px'}}>
            <img style={{height: '63px', width: '63px', marginRight: '15px'}} src={rowObj.img} alt=""/>
            <div style={{display: 'inline-block'}}>
              <div style={{
                marginBottom: '8px',
                color: '#000',
                fontSize: '16px',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
                maxWidth: '250px'
              }}>{rowObj.des}</div>
              <div style={{fontSize: '16px'}}><span style={{fontSize: '30px', color: '#FF6E27'}}>{rowID}</span> 元/任务
              </div>
            </div>
          </div>
        </div>
      );
    };

    return (
      <ListView
        ref={el => this.lv = el}
        dataSource={this.state.dataSource}
        // renderHeader={() => <span>Pull to refresh</span>}
        renderFooter={() => (<div style={{padding: 30, textAlign: 'center'}}>
          {this.state.isLoading ? 'Loading...' : 'Loaded'}
        </div>)}
        renderRow={row}
        renderSeparator={separator}
        useBodyScroll={true}
        pullToRefresh={<PullToRefresh
          refreshing={this.state.refreshing}
          onRefresh={this.onRefresh}
        />}
        onEndReached={this.onEndReached}
        pageSize={5}
      />

    );
  }
}

export default ConListView;
